const execSQL = require('../db/mysql')
function getyyyyMMdd () {
  var d = new Date();
  var curr_date = d.getDate();
  var curr_month = d.getMonth() + 1;
  var curr_year = d.getFullYear();
  String(curr_month).length < 2 ? (curr_month = "0" + curr_month) : curr_month;
  String(curr_date).length < 2 ? (curr_date = "0" + curr_date) : curr_date;
  var yyyyMMdd = curr_year + "/" + curr_month + "/" + curr_date;
  return yyyyMMdd;
}

const getList = (author, key) => {
  let sql = 'select * from bloglist'
  if (author || key) {
    sql += ` where `
  }
  if (author) {
    sql += `author='${author}'`
  }
  if (key) {
    if (author) {
      sql += `and title like '%${key}%'`
    } else {
      sql += `title like '%${key}%'`
    }
  }
  return execSQL(sql)
}

const getDetail = (id) => {
  let sql = `select * from bloglist where id='${id}'`
  return execSQL(sql)
}
const addBlog = (params) => {
  let sql = ` insert into bloglist (title, author, content, date) values ( '${params.title}','${params.author}','${params.content}','${getyyyyMMdd()}' )`
  return execSQL(sql)
}
const update = (params) => {
  let sql = `update bloglist set title='${params.title}', author='${params.author}', content='${params.content}', date='${getyyyyMMdd()}' where id='${params.id}'`
  return execSQL(sql)
}
const deleteBlog = (params) => {
  let sql = `delete from bloglist where id='${params.id}'`
  return execSQL(sql)
}

module.exports = {
  getList,
  getDetail,
  addBlog,
  update,
  deleteBlog
}